package thread;

/**
 * 查看线程的效率
 * 对一个数字进行10亿次自增,测试用循环和线程来执行的时间
 */

public class TestDemo3 {

    //这里测试数据也不能太小,因为创建线程也需要时间
    public static final long Default_Test_Num = 10_0000_0000;

    //普通循环:
    public static void serial(){
        long beg = System.currentTimeMillis();
        long a = 0;
        for (long i = 0 ; i < Default_Test_Num; i++){
            a++;
        }
        long b = 0;
        for (long i = 0 ; i < Default_Test_Num; i++){
            b++;
        }
        long end = System.currentTimeMillis();
        System.out.println("循环执行时间:" + (end - beg) + "ms");
    }

    //利用线程:
    public static void concurrency() throws InterruptedException {
        long beg = System.currentTimeMillis();
        Thread t1 = new Thread(() -> {
            long a = 0;
            for (long i = 0 ; i < Default_Test_Num; i++){
                a++;
            }
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            long b = 0;
            for (long i = 0 ; i < Default_Test_Num; i++){
                b++;
            }
        });
        t2.start();

        //此处不能直接这样记录结束时间,因为求时间戳的代码是在main线程中
        //main与t1,t2是并发执行的,此时两个线程没执行完,就直接记录main函数结束时间了
        //应该让main等待两个线程跑完了再记录结束时间
        t1.join();//main等待t1执行完
        t2.join();//main等待t2执行完

        long end = System.currentTimeMillis();
        System.out.println("线程执行时间:" + (end - beg) + "ms");
    }

    public static void main(String[] args) throws InterruptedException {
        serial();
        concurrency();
    }
}
